local args = ngx.req.get_uri_args();

if args.act_id == nil then
    ngx.say('{"code":10000,"message":"act_id不能为空"}')
    return
end

local act_id = args.act_id
local per_page = tonumber(args.per) or 10
local page = tonumber(args.page) or 1

local redis_client = require "lib.redis"
local redis = redis_client:new()
local ids_key = string.format('ids:%s', act_id)
local total, err = redis:llen(ids_key)

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误","error":"', err,'"}')
    return
end

if total == 0 then
    ngx.say('{"code":200,"message":"success","data":{"total":0,"page":', page, ',"per_page":', per_page,
        ',"scores":{},"items":[]}}'
    )
    return
end

--[[
local max_page = math.ceil(total/per_page)

if page > max_page then
    page = max_page
end
]]

local offset = (page - 1) * per_page

if offset < 0 then
    offset = 0
end

local take = offset + per_page - 1

if take < 0 then
    take = 0
end

local ids, err = redis:lrange(ids_key, offset, take)

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误","error":"', err,'"}')
    return
end

if not ids then
    ngx.say('{"code":200,"message":"success","data":{"total":0,"page":', page, ',"per_page":', per_page,
        ',"scores":{},"items":[]}}'
    )
    return
end

local _scores, err = redis:hmget('scores:'..act_id, unpack(ids))

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误","error":"', err,'"}')
    return
end

local scores = '{'

for of, score in ipairs(_scores) do
    if score ~= ngx.null then
        scores = scores..'"'..ids[of]..'":'..score..','
    end
end

scores = string.sub(scores, 1, -2) .. '}'

local _items, err = redis:lrange('items:'..act_id, offset, take)

if err ~= nil then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"服务器内部错误","error":"', err,'"}')
    return
end

local items = '['

for _, item in ipairs(_items) do
    items = items..item..','
end

items = string.sub(items, 1, -2)..']'

ngx.say('{"code":200,"message":"success","data":{"total":', total, ',"page":', page, ',"per_page":', per_page,
    ',"scores":', scores, ',"items":', items, '}}'
)